import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,propConfig,parseToTopbar} from '../apis/core-util'

export default class MainScope extends Scope {
  constructor(){
    super();
    this.viewKey = 'avg_exec'
    this.$state = {
      topbar:{
        $id:'topbar1',
        loading:true
      },
      sortOptions:_.chain(propConfig).pick('avg_exec','session_count')
      .map(function(v,k){
        return {
          key:k,
          label:v.label
        }
      }).value()
    };
    this.topbarApi = coreApi({
      limit:20,
      classify:'appversion',
      size:1
    },TimeStore.getValue,function(){
      return {
        viewKey:this.viewKey
      }
    }.bind(this),function(){
      if(this.viewKey==='avg_exec'){
        return {
          urlName:'interaction'
        }
      }else if(this.viewKey==='session_count'){
        return {
          urlName:'session'
        }
      }
    },function (){
      return {order:sortMap[this.viewKey]}
    });
  }
  fetch(){
    var _this = this
    this.topbarApi.fetch().then(function(data,params){
      _this.$state.topbar = {
        data:parseToTopbar(data,params)
      }
    },function(err){
      _this.$state.topbar = {
        error:err
      }
    },function(params){
      _this.$state.topbar = {
        loading:true,
        params:params
      }
      _this.emit()
    }).always(function(){
      _this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $changesort(payload){
    this.viewKey = payload.key;
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
